/* 用例测试入口 */
import express from 'express'
import path from 'path'
import createError from 'http-errors' //创建错误状态
import mount from 'mount-routes' //挂载目录多个路由
import indexRouter from './routes/index'
// import testFn from './src' //已迁移至npm run dev执行测试
import config from './config' //导入配置文件
import { brushStep } from './src/utils_html/批量刷步'
const app = express()
const { publicPath, port, host } = config
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(express.static(publicPath))
/* 初始化统一响应客户端机制 */
import responseData from './modules/responseData'
app.use(responseData)
app.use('/', indexRouter)
// 设置跨域和相应数据格式
app.all('/api/*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*') //允许所有主机访问
  res.setHeader('Content-Type', 'application/json;charset=utf-8') //json数据格式
  res.header(
    'Access-Control-Allow-Headers',
    'Content-Type,Content-Length, Authorization, Accept,X-Requested-With'
  ) //添加响应头
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS') //允许的请求方式
  res.header('X-Powered-By', 'piante.cn') //隐藏服务器框架
  if (req.method == 'OPTIONS') res.send(200)
  /*让options请求快速返回*/ else next()
})

//自动挂载routes目录下面的所有路由，以文件名称作为路由的根
mount(app, path.join(process.cwd(), '/routes'), false) //true输出所有路由到控制台
/* 捕获404并转发到错误处理程序 */
app.use((req, res, next) => {
  next(createError(404))
})

/* 处理反馈系统错误 */
app.use((err, req, res, next) => {
  console.log('路由:', req.url)
  if (err) {
    const { referer, host } = req.headers
    const params = {
      referer,
      host,
      url: req.url,
      method: req.method,
    }
    res.status(err.status || 500).json({
      status: err.status || 500,
      data: null,
      ...params,
      message: err.message,
    })
    console.log('系统错误:', err.status, err.message)
  }
  next()
})
// require('./db/mongo/connect')
app.listen(port, () => {
  console.log(`服务器启动成功，服务器地址：http://${host}:${port}`)
  // brushStep()
})
